package sajat.onlab;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import sajat.onlab.AsyncTaskGetRoute.GetRouteCompleteListener;
import sandbox.keki.aut.bme.hu.FriendsAsyncTask;
import sandbox.keki.aut.bme.hu.FriendsAsyncTask.FriendsAsyncTaskListener;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;

public class FriendListFragment extends ListFragment implements GetRouteCompleteListener, FriendsAsyncTaskListener{
	
	private TextView update;
	private ProgressBar updateProgress;
	private SharedPreferences sp;
	private ArrayList<User> List;
	
	 @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
         
		 View view = inflater.inflate(R.layout.friendlistview, null);
         
         update = (TextView) view.findViewById(R.id.updatetext);
         updateProgress = (ProgressBar) view.findViewById(R.id.updateprogress);
         updateProgress.setVisibility(4);
         
         sp = getActivity().getSharedPreferences("logininfo", getActivity().MODE_PRIVATE);
         
         update.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (sp.contains("username")) {
				UpdateFriends();
				}
			}	 
         });
         
         return view;
     }
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (sp.contains("username")) {
			UpdateFriends();
			}
    }
	
	@Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        final User selecteduser = (User)getListAdapter().getItem(position);
        char posacc = getPositionAccuracy();
        
        if (posacc == 2) {
        	GetRoute("	http://maps.googleapis.com/maps/api/directions/xml?origin="+
    				(getPosition().getLatitudeE6()/1E6)+","+(getPosition().getLongitudeE6()/1E6)
    				+"&destination="+selecteduser.getLastPlace().getLatitudeE6()/1E6
    				+","+selecteduser.getLastPlace().getLongitudeE6()/1E6
    				+"&sensor=false");
        }
        
        else if (posacc == 1){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Your position is not accurate. Do you wish to proceed?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                	   GetRoute("	http://maps.googleapis.com/maps/api/directions/xml?origin="+
               				(getPosition().getLatitudeE6()/1E6)+","+(getPosition().getLongitudeE6()/1E6)
               				+"&destination="+selecteduser.getLastPlace().getLatitudeE6()/1E6
               				+","+selecteduser.getLastPlace().getLongitudeE6()/1E6
               				+"&sensor=false");
                   }
               })
               .setNegativeButton("No", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
        }
        
        else Toast.makeText(getActivity(),"Waiting for position...", Toast.LENGTH_LONG).show();
    }

	@Override
	public void onTaskComplete(String[] aText) {
		RouteStep step;
		GeoPoint start;
		GeoPoint end;
		RouteSingleton.getInstance().deleteSteps();
		//while (mytokenizer.hasMoreTokens()) {
		for(int i=0; i<aText.length; i+=8) {
			start = new GeoPoint(
					(int)(Double.parseDouble(/*mytokenizer.nextToken()*/aText[i])*1E6), //latitude
					(int)(Double.parseDouble(/*mytokenizer.nextToken()*/aText[i+1])*1E6)  //longitude
					);
			end = new GeoPoint(
					(int)(Double.parseDouble(/*mytokenizer.nextToken()*/aText[i+2])*1E6), //latitude
					(int)(Double.parseDouble(/*mytokenizer.nextToken()*/aText[i+3])*1E6)	//longitude
					);
			step=new RouteStep(
					start,											//startpoint
					end,											//endpoint
					/*mytokenizer.nextToken()*/aText[i+4],						//polyline
					Double.parseDouble(/*mytokenizer.nextToken()*/aText[i+5]),	//duration
					/*mytokenizer.nextToken()*/aText[i+6],						//instructions
					Double.parseDouble(/*mytokenizer.nextToken()*/aText[i+7])		//distance
					);
			RouteSingleton.getInstance().add(step);
		}
		
		Intent myIntent = new Intent();
		GeoPoint g = getPosition();
		int[] temp = new int[2];
		temp[0] = g.getLatitudeE6();
		temp[1] = g.getLongitudeE6();
		myIntent.putExtra("sajat.onlab.coordinates", temp);
		myIntent.setClassName("sajat.onlab",
		    "sajat.onlab.MyMapActivity");
		startActivity(myIntent);
		
	}

	@Override
	public void onError(String aError) {
		Toast.makeText(getActivity(),"Network error: "+" "+aError, Toast.LENGTH_LONG).show();
		
	}
	
	private GeoPoint getPosition() {
		PositionFragment posfrag = (PositionFragment) getFragmentManager()
        .findFragmentById(R.id.positionfrag);
		return posfrag.getPosition();
	}
	
	private char getPositionAccuracy() {
		PositionFragment posfrag = (PositionFragment) getFragmentManager()
        .findFragmentById(R.id.positionfrag);
		return posfrag.getPositionAccuracy();
	}
	
	public void GetRoute(String URL) {
		AsyncTaskGetRoute getRouteTask = 
            new AsyncTaskGetRoute(getActivity(), this, "Please wait...");
        getRouteTask.execute(URL);
	}
	
	public void UpdateFriends() {
		FriendsAsyncTask frAT = new FriendsAsyncTask(update, updateProgress, sp.getString("username", ""), this);
		frAT.execute();
	}

	@Override
	public void onTaskComplete(ArrayList<User> users) {
		List = users;
		Collections.sort(List, new CustomComparator());
		setListAdapter(new FriendListAdapter(List));
	}
	
	public class CustomComparator implements Comparator<User> {
	    @Override
	    public int compare(User u1, User u2) {
	        return u1.getName().compareTo(u2.getName());
	    }
	}
}
